<template>
  <a-layout
    id="components-layout-demo-custom-trigger"
    style="height: 100%; padding: 0; "
  >
    <a-layout-header class="header">
      <a-row type="flex">
        <a-col class="app-name">
          <!-- <img :src="logo"/>{{ appName }} -->
          <!--          <img src="@/assets/images/logo.png" alt="">-->
          <img :src="portalBackendLogoUrl" alt="">
        </a-col>
        <a-col class="menu-wrapper" flex="1">
          <a-menu
            :theme="theme"
            mode="horizontal"
            class="menu"
            :selected-keys="userOption"
          >
<!--            <a-icon   @click="toPortal" class="home" type="home"/>-->

<!--            <a-sub-menu key="3">
              <div
                slot="title"
                style="height: 60px;line-height: 60px;display: flex;align-items: center;"
                :title="userInfo?userInfo.userName:''"
              >
                <svg-icon icon-class="avatar" class="portrait"/>
                <span class="username">{{ userInfo ? userInfo.userName : '' }}</span>
              </div>
              <a-menu-item @click="changeRole" v-if="roles&&roles.length>1">
                <a-icon type="swap"/>
                {{ roleName }}
              </a-menu-item>
              &lt;!&ndash; <a-menu-item @click="toWallet" v-if="isWalletRole">
                <a-icon type="dollar" />
                {{isOpenWallet ? '我的钱包': '开通钱包'}}
              </a-menu-item> &ndash;&gt;
              &lt;!&ndash; <a-menu-item @click="backToGldBackend">

                返回门户后台
              </a-menu-item> &ndash;&gt;
              <a-menu-item @click="exit">
                <a-icon type="logout"/>
                退出登录
              </a-menu-item>
            </a-sub-menu>-->
          </a-menu>
        </a-col>
      </a-row>
    </a-layout-header>
    <a-layout class="layout" :theme="theme">
      <a-layout-sider
        width="210"
        :class="theme"
        style="overflow-x: hidden;height: calc(100% - 48px); padding-bottom: 20px;"
        collapsible
        breakpoint="lg"
        v-model="collapsed"
      >
        <!-- <template v-slot:trigger>
          <div
            style="font-size:20px;"
            :style="collapsed ? {} : { float: 'right', paddingRight: '10px' }"
          >
            <a-icon :type="collapsed ? 'menu-unfold' : 'menu-fold'"></a-icon>
          </div>
        </template> -->
        <!-- <div class="custom-font" :class="{light:theme==='light'}" v-show="!collapsed">{{ manageTitle }}</div> -->
        <a-menu class="custom-menu" :theme="theme" mode="inline" :inlineIndent="21" :selectedKeys="currentMenu" :inline-collapsed="collapsed" :openKeys.sync="collapsed?[]:openKeys">
          <template v-if="menuTree.length > 0">
            <template v-for="menu in menuTree">
              <a-sub-menu v-if="menu.children" :key="menu.id">
                  <span slot="title">
                    <a-icon v-if="menu.iconUrl" :type="menu.iconUrl"/>
                    <span>{{ menu.text }}</span>
                  </span>
                <a-menu-item
                  v-for="item in menu.children"
                  :key="item.id"
                  @click="clickMenu(item, menu)"
                >{{ item.text }}
                </a-menu-item>
              </a-sub-menu>
              <a-menu-item
                v-else
                @click="clickMenu(menu)"
                :key="menu.id"
              >
                <a-icon v-if="menu.iconUrl" :type="menu.iconUrl"/>
                <span>{{ menu.text }}</span>
              </a-menu-item>
            </template>
          </template>
        </a-menu>
      </a-layout-sider>
      <a-layout-content>
        <!-- Content -->
        <router-view name="main"></router-view>
      </a-layout-content>
    </a-layout>
<!--    <choose-role :show="showRole" :allow-cancel="allowRoleCancel" :current-role="roleCode" :role-list="roles"  @ok="handleChooseRole" @cancel="handleCancelChoose"></choose-role>-->
<!--    <open-wallet :show="openWalleShow" :loading="confirmLoading" @cancel="cancelOpenWallet" @ok="handleOpenWallet"></open-wallet>-->
  </a-layout>
</template>
<script>
import {mapState} from 'vuex'
// import {manageTitleMap, roleCodeMap} from '@/config'
import storage from '@/utils/storage'
// import ChooseRole from '../../components/base/ChooseRole'
import {appConfig} from '../../config/app'
// import {getLoginUrl} from '../../api/portalSetting'
// import {roleMixin} from '@/mixins'
// import {ssoLogout} from '../../api/sso'
// import {queryWallet, openWallet, balanceInquiry} from '@/api/wallet'
// import OpenWallet from '@/components/base/OpenWallet'

// const logo = require('../../../static/logo.png')
// let appName = require('../../config/app').appName

export default {
  // components: {ChooseRole, OpenWallet},
  // mixins: [roleMixin],
  data () {
    return {
      imageUrl: '',
      manageTitleMap: [],
      roleCodeMap: [],
      menuTree: [],
      menuIdx: 0,
      roles: storage.session.get('roles'),
      showRole: false,
      allowRoleCancel: false,
      confirmLoading: false,
      isOpenWallet: false,
      openWalleShow: false,
      // logo,
      // appName,
      manageTitle: '',
      roleName: '',
      isRoleCheck: false,
      userOption: [],
      userInfo: storage.session.get('userInfo'),
      portalSettingsInfo: storage.session.get('portalSettingsInfo'),
      portalBackendLogoUrl: '',
      currentMenu: [],
    }
  },
  watch: {
    portalSettingsInfo: {
      handler(newVal) {
        console.log(newVal,'newVal')
        if (newVal){
          this.portalBackendLogoUrl = newVal.portalBackendLogoUrl // 后台
          console.log(this.portalBackendLogoUrl,'this.portalBackendLogoUrl')
        }
        // this.fileList = []
        // this.fileList.unshift(...this.defaultFileList)
      },
      immediate: true,
      deep: true
    }
  },
  created () {
    // console.log('storage.session.get(\'portalSettingsInfo\')',storage.session.get('portalSettingsInfo'))
    // let portalSettingsInfo = storage.session.get('portalSettingsInfo')
    // this.portalBackendLogoUrl = portalSettingsInfo.portalBackendLogoUrl // 后台
    // console.log('portalBackendLogoUrl',this.portalBackendLogoUrl)
    let role = storage.session.get('role')
    if (!role) {
      if (this.roles && this.roles.length > 0) {
        if (this.roles.length === 1) {
          this.handleChooseRole(this.roles[0])
        } else {
          this.showRole = true
        }
      } else {
        // this.toGldPortal()
      }
    } else {
      this.manageTitle = this.manageTitleMap[role] || ''
      this.roleName = this.roleCodeMap[role] || ''
      // this.menuTree = appConfig.menuList || [];
      this.menuTree = [{
        name: 'text',
        url: '/catalogSort',
        children: [{
          name: '商品分类',
          url: '/',
        }]
      }];

      if (this.isWalletRole&&this.orgId) this.getWallet()
    }
    // 目前无多级菜单，不好调试。暂时处理
    // this.$watch('$route.path', data => {
    //   this.manageTitle = this.manageTitleMap[storage.session.get('role')] || ''
    //   this.roleName = this.roleCodeMap[storage.session.get('role')] || ''
    //   // this.menuTree = appConfig.menuList || []
    //   const cur = this.menuTree.filter(item => item.url === data)
    //   if (cur.length == 0) {
    //     this.menuTree.some(item => item.children && item.children.length > 0 ? item.children.find(item => item.url === data) : '')
    //   }
    // }, {immediate: true})
    this.menuTree = [{
      text: '商品管理',
      url: '/',
      children: [{
        text: '目录分类',
        url: 'catalogSort',
        id: 11
      },{
        text: '商品仓库',
        url: 'goodsConfig',
        id: 12
      },{
        text: '商品配置',
        url: 'goodsSort',
        id: 13
      }]
    }];
  },
  computed: {
    // ...mapState(['currentMenu', 'currentMenuTitle']), //, "menuTree"
    // roleName(){
    //   let role = storage.session.get('role')
    //   return roleCodeMap[role]
    // },
    openKeys:{
      get () {
        return this.$store.state.openMenu
      },
      set (val) {
        this.$store.commit('setOpenMenu', val)
      }
    },
    key () {
      return this.$route.fullPath // + Math.random();
    },
    isWalletRole(){
      let role = storage.session.get('role')
      let walletRole = [
        'DATA_PRODUCER', // 提供方
        'DATA_BUSINESS', // 数商
        'DATA_REQUESTER', // 需求方
        'DT_THIRD_SERVERS' // 第三方
      ]
      return walletRole.findIndex(i=>i == role) !== -1
    },
    orgId () {
      // if (process.env.NODE_ENV === 'development') return storage.session.get('role') //'DATA_BUSINESS'
      let info = storage.session.get('userInfo')
      return info ? (info.deptId || '') : ''
    },
    collapsed: {
      get: function () {
        return this.$store.state.isCollapsed
      },
      set: function (val) {
        this.$store.commit('setCollapsed', val)
      }
    },
    theme: {
      get: function () {
        return this.$store.state.theme
      },
      set: function (val) {
        this.$store.commit('setTheme', val)
      }
    },
  },
  methods: {
    async getWallet () {
      let wallet = {}
      let res = await queryWallet({orgId: this.orgId})
      if(res.code === 0 && res.data.length !== 0){
        wallet = res.data[0]
        this.isOpenWallet = true
        if(wallet.status == 0)return;
        try{
          let res = await balanceInquiry({accountNo:wallet.virtualCardNo});
          wallet.balance = res.data
        }catch(e){
          //TODO handle the exception
        }
      }
      storage.session.set('wallet',wallet)
      this.isOpenWallet = res.code === 0 && res.data.length !== 0

    },
    async handleOpenWallet (values) {
      this.confirmLoading = true
      values.orgId = this.orgId
      try {
        let { code } = await openWallet(values)
        if (code !== 0) return this.$message.warn('开通失败')
        this.$message.success('开通成功')
        this.cancelOpenWallet()
        this.getWallet()
      } catch (e) {
        this.$message.warn('开通失败')
      }
    },
    cancelOpenWallet () {
      this.confirmLoading = false
      this.openWalleShow = false
    },
    toWallet () {
      // if (this.isOpenWallet)location.href = location.origin + '/sjsc/pay/'
      if (this.isOpenWallet) this.$router.push({path: '/wallet'})
      else this.openWalleShow = true
    },
    backToGldBackend () {
      this.userOption = []
      if (appConfig.portalBackendUrl) {
        location.href = appConfig.portalBackendUrl
      } else {
        getLoginUrl().then(res => {
          if (res.code === 0) {
            appConfig.loginUrl = res.data.purLoginUrl
            appConfig.portalUrl = res.data.portalUrl
            appConfig.portalBackendUrl = res.data.portalBackendUrl
            if (appConfig.portalBackendUrl) { window.location.href = appConfig.portalBackendUrl }
          }
        })
      }
    },
    changeTheme () {
      this.theme = this.theme === 'dark' ? 'light' : 'dark'
    },
    exit () {
      this.userOption = []
      const that = this
      this.$confirm({
        content: '确认退出？',
        onOk: () => {
          that.toGldPortal()
        }
      })
    },
    removeAll () {
      storage.session.remove('isLogin')
      storage.session.remove('authToken')
      storage.session.remove('userInfo')
      storage.session.remove('topPermTree')
      storage.session.remove('role')
      storage.session.remove('roles')
      storage.session.remove('topPermTree')
      appConfig.menuList = []
    },
    toGldPortal () {
      const gldToken = storage.session.get('gldToken')
      if (gldToken) {
        // 存在token 调用退出登录
        ssoLogout({token: gldToken}).then(() => {
          this.removeAll()
          storage.session.remove('gldToken')
          window.open('https://tradetest.szggzy.com/ggzy/center/#/login', '_blank')

          // this.toGldLogin()
        }).catch(() => {
          this.removeAll()
          storage.session.remove('gldToken')
          window.open('https://tradetest.szggzy.com/ggzy/center/#/login', '_blank')

          // this.toGldLogin()
        })
      } else {
        this.removeAll()
        // this.toGldLogin()
        window.open('https://tradetest.szggzy.com/ggzy/center/#/login', '_blank')

      }
    },
    toGldLogin () {
      if (appConfig.loginUrl) {
        window.location.href = appConfig.loginUrl
      } else {
        getLoginUrl().then(res => {
          if (res.code === 0) {
            appConfig.loginUrl = res.data.purLoginUrl
            appConfig.portalUrl = res.data.portalUrl
            appConfig.portalBackendUrl = res.data.portalBackendUrl
            if (appConfig.loginUrl) { window.location.href = appConfig.loginUrl }
          }
        })
      }
    },
    clickMenu (item) {
      let { url, id, text } = item
      console.log(url,'url')
      // this.$router.push('/goodsSort');
      this.currentMenu = [id]
      // id && this.$store.commit('setCurrentMenu', id)
      // text && this.$store.commit('setCurrentMenuTitle', text)
      this.$router.push({path: '/' + url})
    },
    handleChooseRole (role) {
      storage.session.set('role', role)

      // storage.session.set('userInfo', JSON.parse( JSON.stringify( {userName: roleCodeMap[role]}) ) )
      // this.$set(this.userInfo,'userName',roleCodeMap[role])

      console.log(role,'role')
      this.showRole = false
      this.allowRoleCancel = false
      let { name, fullPath, query } = this.$route
      if(name=='index'||name=='/'){
        this.$router.go(0)
      }else{
        this.$store.commit('setIsLogin', false)
        // 处理通知详情跳转 手动切换
        query = this.isRoleCheck ? { fullPath } : {};
        this.$router.push({path: '/', query})
      }
      // this.menuTree = menuMap[storage.session.get('role')]
      // this.menuTree = appConfig.menuList
      // this.manageTitle = this.manageTitleMap[storage.session.get('role')] || ''
    },
    handleCancelChoose () {
      this.showRole = false
      this.allowRoleCancel = false
    },
    toPortal () {
      location.href = location.origin + '/sjsc/'
    },
    changeRole () {
      this.userOption = []
      this.allowRoleCancel = true
      this.showRole = true
      this.isRoleCheck = true
    }
  }
}
</script>
<style lang="scss" scoped>
@import "src/assets/css/constants.scss";

.header {
  background-color: #fff;
  height: 60px;
  line-height: 60px;
  padding: 0 20px;

  .app-name {
    cursor: pointer;
    color: white;
    font-size: 18px;
    font-family: MicrosoftYaHei-Bold, MicrosoftYaHei, sans-serif;
    font-weight: bold;
    display: flex;
    align-items: center;

    img {
      width: 150px;
      margin-right: 30px;
      margin-left: 10px;
    }
  }
}

.menu-wrapper {
  text-align: right;

  .menu {
    line-height: 60px;
    height: 60px;

    .portrait {
      width: 32px;
      height: 32px;
    }

    .username {
      margin-left: 8px;
      font-size: 14px;
      font-family: MicrosoftYaHei, sans-serif;
      color: #000;
    }
  }

  /deep/ .ant-menu-dark, .ant-menu-dark .ant-menu-sub {
    background: $dark-header-bg;
  }

  /deep/ .ant-menu-dark.ant-menu-horizontal > .ant-menu-submenu {
    background: $dark-header-bg;
  }
}

.layout {

  .dark {
    background: $dark-menu-bg;

    /deep/ .ant-layout-sider-trigger {
      background: $light-bg;

      i {
        color: $light-bg;
      }
    }

    /deep/ .ant-menu-item:hover {
      background: $dark-menu-hover;
    }
  }

  .light {
    background: $light-bg;
    border-top: 1px solid #e8e8e8;
    border-right: 1px solid #e8e8e8;
    /deep/ .ant-layout-sider-trigger {
      background: $light-bg;

      i {
        color: $dark-menu-bg;
      }
    }

    /deep/ .ant-menu-item:hover {
      background: #e6f7ff;
    }
  }

  /deep/ .ant-menu-inline > .ant-menu-submenu > .ant-menu-submenu-title {
    margin: 0 !important;
  }

  .ant-menu-submenu {
    user-select: none;
  }

  .ant-menu-submenu-title:hover {
    background: white;
  }

  .ant-menu-dark, .ant-menu-dark .ant-menu-sub, .ant-menu-dark .ant-menu-item {
    background: $dark-menu-bg;
  }

  .ant-menu-inline .ant-menu-item {
    margin: 0;
  }

  .ant-menu.ant-menu-dark .ant-menu-item-selected, .ant-menu-submenu-popup.ant-menu-dark .ant-menu-item-selected {
    background: $dark-menu-active;
  }

  .ant-menu-inline, .ant-menu-vertical, .ant-menu-vertical-left {
    border-right: none !important;
  }
}

.rightBtnAll {
  display: flex;
  margin-right: 20px;
  cursor: pointer;
}

.userInfo {
  margin-right: 20px;
}

.loginout {
  color: #1890ff;
}

/* 设置滚动条的样式 */
.ant-layout-sider-dark::-webkit-scrollbar {
  width: 8px;
}

/* 滚动槽 */
.ant-layout-sider-dark::-webkit-scrollbar-track {
  -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
  border-radius: 10px;
}

/* 滚动条滑块 */
.ant-layout-sider-dark::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: #b4d4f3a3;
  -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.5);
}

.custom-font {
  font-size: 16px;
  font-family: Roboto, sans-serif;
  line-height: 48px;
  color: white;
  font-weight: bold;
  padding-left: 21px;

  &.light {
    color: $dark-header-bg;
  }
}
.home {
  font-size: 20px;
  margin-right: 20px;
}
</style>
